package logic

import (
	"context"
	"errors"
	"logincheck/model/cache"
	"logincheck/model/mysql"
	"logincheck/pkg"

	"logincheck/logincheckrpc/internal/svc"
	"logincheck/logincheckrpc/logincheckrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *logincheckrpc.LoginRequest) (*logincheckrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	user := mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	err := user.FindUser(mysql.DB, user.ID)
	if err != nil {
		return nil, err
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, errors.New("密码不正确")
	}
	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.Captcha != result {
		return nil, errors.New("图形验证码不正确")
	}
	result1, _ := cache.Rdb.Get(l.ctx, "send"+in.Account).Result()
	if in.Mobile != result1 {
		return nil, errors.New("短信验证码不正确")
	}
	return &logincheckrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
